AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )

include('shared.lua')

function ENT:Initialize()
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
	self.Entity:SetSolid( SOLID_VPHYSICS )

	local phys = self.Entity:GetPhysicsObject()
	
	if (phys:IsValid()) then
		phys:Wake()
	end

	self.Entity:SetVar( 'LastFireTime', 0 )
end



function ENT:PhysicsUpdate( physobj )
	local kb = self.Entity:GetVar('Kickback', 0)
	
	if kb > 0 then
		local kbt = self.Entity:GetVar('KickbackTime',0)
		physobj:ApplyForceCenter(self.Entity:GetUp()*-1*kb)
		if CurTime() > kbt then
			self.Entity:SetVar('Kickback',0)
		end
	end
end

local function Fire( ply, ent)
	if (!ent:IsValid()) then return false end
	if !ply then return false end
	ent:SetVar('Firing',true)
	local LastFireTime = ent:GetVar('LastFireTime', 0)
	local ctype = ent:GetVar('CannonType','cannon')
	local sd = ent:GetVar('selfdestruct',15.0)
	
	if (LastFireTime + cannon_types[ctype].delay) > CurTime() then return end
	
	ent:SetVar( 'LastFireTime', CurTime() )
	
	local round = ents.Create( "malawar_cannonround" )
		round:SetModel("models/Items/combine_rifle_ammo01.mdl")
		round:SetVar('Owner',ply)
		round:SetVar('selfdestruct',sd)
		SetupCannonRound(round, cannon_types[ctype])
		round:SetPos( ent:GetPos() + (ent:GetUp()*ent:OBBMaxs().z))

		local Ang = ent:GetAngles()
		
		

		ent:EmitSound(cannon_types[ctype].sound,10)

		round:SetAngles(Ang)
	round:Spawn()


	local effectdata = EffectData()
		effectdata:SetOrigin( ent:GetPos() + (ent:GetUp()*ent:OBBMaxs().z) )
		effectdata:SetMagnitude( cannon_types[ctype].shellradius )
		effectdata:SetScale( cannon_types[ctype].shellradius )
		effectdata:SetRadius( cannon_types[ctype].shellradius )
		effectdata:SetAngle(Ang)
	util.Effect( cannon_types[ctype].effect, effectdata, true, true )

	local phys = round:GetPhysicsObject()
	local mass = cannon_types[ctype].shellmass or 15
	phys:SetMass(mass)
	phys:SetVelocity((ent:GetUp())*cannon_types[ctype].power + ent:GetVelocity())
	ent:SetVar('Kickback',cannon_types[ctype].kickback * 10)
	ent:SetVar('KickbackTime',CurTime() + 0.2)
	ent:GetPhysicsObject():Wake()
end

local function EndFire( ply, ent )
	if (!ent:IsValid()) then return false end
	ent:SetVar('Firing',false)
end

function ENT:Think()
	if self.Entity:GetVar('Firing',false) then
		Fire(self.Entity:GetVar('Owner',nil),self.Entity)
	end
end

numpad.Register( "Cannon_On", Fire )
numpad.Register( "Cannon_Off", EndFire )
